package cn.south.campus.common.file.service;

import cn.south.campus.common.config.FileUploadConfig;
import cn.south.campus.common.exceptions.BusinessException;
import cn.south.campus.common.file.vo.FileVO;
import cn.south.campus.common.model.enums.CommonEnums;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;

/**
 * <p>
 *
 * </p>
 *
 * @author chow
 * @since 2023/3/16 17:38
 */
@Service
public class LocalUploadServiceImpl extends AbstractFileUploadService implements IFileService {

    @Resource
    private FileUploadConfig fileUploadConfig;

    @Override
    public String getFileUrl(String objectName) {
        return null;
    }

    @Override
    public String type() {
        return "local";
    }

    @Override
    protected void uploadFile(FileVO fileBO, MultipartFile file) {
        String fileName = fileBO.getFileName();
        String localFilePath = fileUploadConfig.getLocalFilePath();
        String localFilePrefix = fileUploadConfig.getLocalFilePrefix();
        String domain = fileUploadConfig.getDomain();
        String absPath = getAbsoluteFile(localFilePath + "/", fileName).getAbsolutePath();
        try {
            file.transferTo(Paths.get(absPath));
            fileBO.setActionUrl(domain + "/" + localFilePrefix + "/" + fileName);
        } catch (IOException e) {
            throw new BusinessException(CommonEnums.FILE_UPLOAD_ERROR);
        }
    }


    private File getAbsoluteFile(String uploadDir, String fileName) {
        File desc = new File(uploadDir + File.separator + fileName);
        if (!desc.exists() && !desc.getParentFile().exists()) {
            boolean mkdirs = desc.getParentFile().mkdirs();
        }
        return desc.isAbsolute() ? desc : desc.getAbsoluteFile();
    }
}
